package com.bst.etl.batch.job;


import com.bst.common.constant.JobConstant;
import com.bst.common.exception.base.BaseException;
import com.bst.etl.batch.listener.BeforeDwJobListener;
import com.bst.etl.batch.processor.DimDataCheckProcessor;
import com.bst.etl.batch.processor.KeyToUpperProcessor;
import com.bst.etl.batch.tasklet.InsertDimTasklet;
import com.bst.etl.batch.tasklet.MsgSendTasklet;
import com.bst.etl.vo.JobShareDataVO;
import com.bst.md.domain.MdMedPubfld;
import com.bst.md.service.IMdMedDimService;
import com.bst.md.service.IMdMedPubfldService;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.TaskletStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class OdsToDwJob extends BaseJob {

    public OdsToDwJob() {
        super();
    }

    @Autowired
    KeyToUpperProcessor keyToUpperProcessor;
    @Autowired
    IMdMedDimService mdMedDimService;
    @Autowired
    IMdMedPubfldService mdMedPubfldService;


    @Bean
    public Job odsToDwJobBean() throws BaseException {
        TaskletStep beforeStep = super.buildBeforeStep();
        JobShareDataVO jobShareDataVO = new JobShareDataVO();
        List<MdMedPubfld> pubfldList = mdMedPubfldService.findByFldPrefix(JobConstant.ID_DIM_PREX);
        jobShareDataVO.setPubfldList(pubfldList);
        TaskletStep mainStep = this.buildMainStep(jobShareDataVO);
        TaskletStep afterDimStep = this.buildAfterDimStep(jobShareDataVO);
        Job job = jobBuilderFactory.get("odsToDwJobBean")
                .incrementer(new RunIdIncrementer())
                .listener(new BeforeDwJobListener(jobShareDataVO))
                .start(beforeStep).next(mainStep).next(afterDimStep).next(msgSendStep(jobShareDataVO))
                .build();
        return job;
    }

    protected TaskletStep buildMainStep(JobShareDataVO jobShareDataVO) throws BaseException {
        TaskletStep step = stepBuilderFactory.get("main_step")
                .<Map, Map>chunk(1024)
                .reader(selfJdbcCursorItemReader)
                .processor(new DimDataCheckProcessor(jobShareDataVO))
                .writer(noPkInsertWriter)
                .build();
        return step;
    }

    protected TaskletStep buildAfterDimStep(JobShareDataVO jobShareDataVO ) {
        TaskletStep step = this.stepBuilderFactory.get("AfterDimStep")
                .tasklet(new InsertDimTasklet(jobShareDataVO))
                .build();
        return step;
    }

    protected TaskletStep msgSendStep(JobShareDataVO jobShareDataVO) {
        TaskletStep step = this.stepBuilderFactory.get("msgSendStep")
                .tasklet(new MsgSendTasklet(jobShareDataVO))
                .build();
        return step;
    }
}
